package com.legendframework.dao.page;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分页工具
 */
public class PageUtil {

    private PageUtil(){}


    /**
     * 开始分页
     * @param list 集合
     * @param currentPage 页码(1开始)
     * @param itemNum 每页显示条目数
     * @param <T> 泛型
     * @return 分页对象
     */
    public static <T> Page<T> page(Collection<T> list , long currentPage , long itemNum){
        list = list == null ? new ArrayList<>() : list;
        currentPage = currentPage <= 0 ? 1 : currentPage;
        itemNum = itemNum <= 0 ? 5 : itemNum;
        Page<T> pageBean = new Page<>(currentPage,itemNum);
        List<T> data = list.stream().skip(itemNum * (currentPage - 1)).limit(itemNum).collect(Collectors.toList());
        pageBean.setList(data);
        pageBean.setTotalSum(list.size());
        pageBean.setTotalPage((list.size() % itemNum != 0 ? list.size() / itemNum + 1 : list.size() / itemNum));
        return pageBean;
    }

}
